package com.nf.health.app.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.hyphenate.exceptions.HyphenateException;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.chatservice.activity.ChatActivityGroup;
import com.nf.health.app.activity.global.MainActivity;
import com.nf.health.app.chatservice.activity.ChatActivity;
import com.nf.health.app.customview.MyListView;
import com.nf.health.app.models.SystemMsgBean;
import com.nf.health.app.utils.ScreentUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by fei on 2016/3/10.
 */
public class ConversationListFragment extends IBaseFragment {

    private static final String FLAG_SYS_MSG = "systemMsg";
    @Bind(R.id.titlebar_back_view)
    ImageView titlebarBackView;
    @Bind(R.id.titlebar_title_tv)
    TextView titlebarTitleTv;
    @Bind(R.id.list)
    EaseConversationList conversationListView;//会话列表控件
    @Bind(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.ll_container)
    LinearLayout ll_container;
    @Bind(R.id.rl_noMessage)
    RelativeLayout rlNoMessage;
    @Bind(R.id.fl_chatList)
    View flChatList;

    private final static int MSG_REFRESH = 2;
    protected List<EMConversation> conversationList = new ArrayList<EMConversation>();
    List<SystemMsgBean> systemMsgAll = new ArrayList<>();
    protected boolean hidden;
    protected boolean isConflict;
    MyListView myListView;
    private MainActivity mainActivity;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addViewFillInRoot(R.layout.fragment_conversation_list);
        ButterKnife.bind(this, rootView);
        mainActivity = (MainActivity) getActivity();

        titlebarBackView.setVisibility(View.GONE);
        titlebarTitleTv.setText(R.string.main_tab_msg);

        swipeRefreshLayout.setColorSchemeResources(R.color.theme_color, android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_orange_light);

        setUpView();

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadConversationList();
            }
        });

        if (Build.VERSION.SDK_INT >= 14) {
            int statusBarHeight = ScreentUtils.getStatusBarHeight(getActivity().getBaseContext());
            ll_container.setPadding(0, statusBarHeight, 0, 0);
            Window window = getActivity().getWindow();
        }
//        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (SystemMsgBean.QUESTIONNAIRE_SURVEY.equals(systemMsgAll.get(position).getType())) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString(QuestionSurveyActivity.EXTRA_TYPE, systemMsgAll.get(position).getType());
//                    ActivityUtils.showActivity(getActivity(), QuestionSurveyActivity.class, bundle);
//                } else {
//                    Bundle bundle = new Bundle();
//                    bundle.putString(MessageDetailActivity.EXTRA_TYPE, systemMsgAll.get(position).getType());
//                    ActivityUtils.showActivity(getActivity(), MessageDetailActivity.class, bundle);
//                }
//            }
//        });
    }


    @Override
    public void handleActionStart(String actionName, Object object) {
        if (swipeRefreshLayout.isRefreshing()) {

        } else {
            super.handleActionStart(actionName, object);
        }
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        super.handleActionFinish(actionName, object);
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {

    }

    private void setUpView() {
        conversationList.addAll(loadConversationList());
        conversationListView.init(conversationList);

        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (conversationList.size() > 0) {
//                    position = position - 1;
//                }
                EMConversation conversation = conversationListView.getItem(position);
                String doctorType = null;
                try {
                    doctorType = conversation.getLastMessage().getStringAttribute(Constants.EMContact.EF_DoctorType);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent();
                intent.putExtra(EaseConstant.EXTRA_USER_ID, conversation.getUserName());
                int chatType = (conversation.getType() == EMConversation.EMConversationType.GroupChat) ? EaseConstant.CHATTYPE_GROUP : EaseConstant.CHATTYPE_SINGLE;
                if (chatType == EaseConstant.CHATTYPE_SINGLE) {
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, chatType);
                    intent.putExtra(ChatActivity.EXTRA_DOCTOR_TYPE, doctorType);
                    intent.setClass(getActivity(), ChatActivity.class);
                    startActivity(intent);
                } else if (chatType == EaseConstant.CHATTYPE_GROUP) {
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, chatType);
                    intent.setClass(getActivity(), ChatActivityGroup.class);
                    startActivity(intent);
                }
            }
        });

        EMClient.getInstance().addConnectionListener(connectionListener);

        registerForContextMenu(conversationListView);
    }

    protected EMConnectionListener connectionListener = new EMConnectionListener() {

        @Override
        public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                isConflict = true;
            } else {
                handler.sendEmptyMessage(0);
            }
        }

        @Override
        public void onConnected() {
            handler.sendEmptyMessage(1);
        }
    };

    protected Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    onConnectionDisconnected();
                    break;
                case 1:
                    onConnectionConnected();
                    break;

                case MSG_REFRESH: {
                    conversationList.clear();
                    conversationList.addAll(loadConversationList());
                    conversationListView.refresh();
                    mainActivity.updateUnreadLabel();//更新未读信息红点
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 连接到服务器
     */
    protected void onConnectionConnected() {
//        hideDataError();
    }

    /**
     * 连接断开
     */
    protected void onConnectionDisconnected() {
//        showDataError();
    }

    /**
     * 获取会话列表
     *
     * @return +
     */
    protected List<EMConversation> loadConversationList() {
        // 获取所有会话，包括陌生人
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }

        if (list.size() ==0){
            flChatList.setVisibility(View.GONE);
            rlNoMessage.setVisibility(View.VISIBLE);
        }else{
            flChatList.setVisibility(View.VISIBLE);
            rlNoMessage.setVisibility(View.GONE);
        }
        swipeRefreshLayout.setRefreshing(false);
        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden && !isConflict) {
            refresh();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!hidden) {
            refresh();
        }
    }

    /**
     * 刷新页面
     */
    public void refresh() {
        if (!handler.hasMessages(MSG_REFRESH)) {
            handler.sendEmptyMessage(MSG_REFRESH);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        boolean deleteMessage = false;
        if (item.getItemId() == R.id.delete_message) {
            deleteMessage = true;
        } else if (item.getItemId() == R.id.delete_conversation) {
            deleteMessage = false;
        }
        int pos = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
        EMConversation tobeDeleteCons = conversationListView.getItem(pos);
        if (tobeDeleteCons == null) {
            return true;
        }
        try {
            //取得聊天的userId
            String userName = tobeDeleteCons.getUserName();
////            //存储"3",表示已经评价(状态),再次接收到信息会产生问题
//            DbManager.getInstance().saveChatTime(userName, "3");
            // 删除此会话
            EMClient.getInstance().chatManager().deleteConversation(userName, deleteMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        refresh();
        // 更新消息未读数
        return true;
    }

}
